<?php

namespace lico\Tool\Model;

use lico\Runtime\Config;

use lico\Container;

class Pdo
{

    protected static $conn = null;
    protected $PDOStatement;

    public function __construct()
    {
        $this->collection();
    }

    public static function connect()
    {
        $config = Container::getBowl('lico\Runtime\Config')->get('database');
        $type = $config['type'];
        $host = $config['hostname'];
        $port = $config['hostport'];
        $database = $config['database'];
        $username = $config['username'];
        $password = $config['password'];
        $extra = $config['option'];

        try {
            self::$conn = new \PDO($type . ':host=' . $host . ';port=' . $port . ';dbname=' . $database, $username, $password, $extra);
        } catch (\PDOException $e) {
            de($e->getMessage());
        }
        return self::$conn;
    }

    /**
     * 连接实例
     */
    public function collection()
    {
        if (is_null(self::$conn)) {
            self::connect();
        }
        return self::$conn;
    }

    /**
     * 执行sql
     */
    public function query($sql)
    {
        $this->PDOStatement = self::$conn->query($sql);
        return $this;
    }

    /**
     * 返回数组集
     */
    public function fetchAll()
    {
        return $this->PDOStatement->fetchAll(\PDO::FETCH_ASSOC);
    }

    /**
     * 返回数组--列
     */
    public function column($key, $value = "")
    {

        if ($key && !$value) {
            $param = \PDO::FETCH_UNIQUE;
        } elseif ($key && (trim($value) == "*" || stripos($value, ','))) {
            $param = \PDO::FETCH_UNIQUE | \PDO::FETCH_ASSOC;
        } else {
            $param = \PDO::FETCH_UNIQUE | \PDO::FETCH_COLUMN;
        }

        $result = $this->PDOStatement->fetchAll($param);
        return $result;
    }

    /**
     * 防止克隆
     */
    private function __clone()
    {
    }
}
